package org.dromara.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.LzshBusinessInfo;
import org.dromara.business.domain.LzshBusinessInfoDataTotal;
import org.dromara.business.domain.LzshTemplate;
import org.dromara.business.domain.bo.LzshTemplateBo;
import org.dromara.business.domain.vo.LzshTemplateVo;
import org.dromara.business.mapper.LzshBusinessInfoMapper;
import org.dromara.business.mapper.LzshTemplateMapper;
import org.dromara.business.service.ILzshTemplateService;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 表单管理Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-19
 */
@RequiredArgsConstructor
@Service
public class LzshTemplateServiceImpl implements ILzshTemplateService {

    private final LzshTemplateMapper baseMapper;

    private final LzshBusinessInfoMapper infoMapper;

    /**
     * 查询表单管理
     *
     * @param id 主键
     * @return 表单管理
     */
    @Override
    public LzshTemplateVo queryById(Long id){
        return baseMapper.queryById(id);
    }

    /**
     * 分页查询表单管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 表单管理分页列表
     */
    @Override
    public List<LzshTemplateVo> queryPageList(LzshTemplateBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<LzshTemplate> lqw = buildQueryWrapper(bo);
//        Page<LzshTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<LzshTemplateVo> result;
        int size = pageQuery.getPageSize();
        int num  = ( pageQuery.getPageNum() - 1 ) * 10;
        if (bo.getTitle() != null) result = baseMapper.selectAllByTitle(size, num, bo.getTitle());
        else result = baseMapper.selectAll(size, num);
        return result;
    }

    /**
     * 查询符合条件的表单管理列表
     *
     * @param bo 查询条件
     * @return 表单管理列表
     */
    @Override
    public List<LzshTemplateVo> queryList(LzshTemplateBo bo) {
        LambdaQueryWrapper<LzshTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<LzshTemplate> buildQueryWrapper(LzshTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LzshTemplate> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), LzshTemplate::getTitle, bo.getTitle());
        return lqw;
    }

    /**
     * 新增表单管理
     *
     * @param bo 表单管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(LzshTemplateBo bo) {
        LzshTemplate add = MapstructUtils.convert(bo, LzshTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改表单管理
     *
     * @param bo 表单管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(LzshTemplateBo bo) {
        LzshTemplate update = MapstructUtils.convert(bo, LzshTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(LzshTemplate entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除表单管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public long queryCount(LzshTemplateBo bo) {
        LambdaQueryWrapper<LzshTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectCount(lqw);
    }

    /**
     * 查询每个标题的数量
     * @return
     */
    @Override
    public Map<String, List<LzshBusinessInfoDataTotal.totalData2>> getTemplateNum() {
        //获取所有模板值
        List<LzshTemplate> listTemplate = baseMapper.selectList(null);
        Map<String, Integer> nameCountMap = new HashMap<>(); // 创建一个Map来存储每个name出现的次数
        for (LzshTemplate item : listTemplate) {
            if (item.getTitle() != null) {
                String name = item.getTitle();
                nameCountMap.put(name, 0);
            }
        }
        //获取所有businessinfo
        List<LzshBusinessInfo> businessInfoList = infoMapper.selectList();
        for (int i = 0; i < businessInfoList.size(); i++) {
            for (int j = 0; j < listTemplate.size(); j++) {
                if (businessInfoList.get(i).getTemplateId().equals(listTemplate.get(j).getId())) {
                    String name = listTemplate.get(j).getTitle();
                    nameCountMap.put(name, nameCountMap.getOrDefault(name, 0) + 1);
                    break;
                }
            }
        }
        //遍历map,把每个元素封装回去
        Map<String, List<LzshBusinessInfoDataTotal.totalData2>> result = new HashMap<>();
        List<LzshBusinessInfoDataTotal.totalData2> totalData2List = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : nameCountMap.entrySet()) {
            LzshBusinessInfoDataTotal.totalData2 data = new LzshBusinessInfoDataTotal.totalData2();
            data.setName(entry.getKey());
            data.setValue((long) entry.getValue());
            totalData2List.add(data);
        }
        result.put("source",totalData2List);
        return result;
    }
}
